package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.AddressManageAdapter;
import xhwl.hmo.mall.http.api.AddressListApi;
import xhwl.hmo.mall.http.api.DelAddressApi;
import xhwl.hmo.mall.http.bean.resp.AddressListResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.views.MyDialog;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.pulltorefresh.callback.PullToRefreshListener;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 地址管理
 */
public class AddressManageActivity extends BaseActivity implements PullToRefreshListener {

    public static final String EXTRA_SHOW_CONFIRM_DIALOG ="showDialog" ;
    private PullToRefreshRecyclerView recyclerView;
    Button btnAdd;
    AddressManageAdapter adapter;
    int mPage = 1;
    List<AddressListResp.Address> mList=new ArrayList<>();
    MyDialog myDialog;
    boolean showDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showDialog=getIntent().getBooleanExtra(EXTRA_SHOW_CONFIRM_DIALOG,true);
        setContentView(R.layout.activity_address_manage);
    }

    @Override
    public void initViews() {
        initTitleViews();
        btnAdd= (Button) findViewById(R.id.btnAdd);
        recyclerView = (PullToRefreshRecyclerView) findViewById(R.id.recyclerView);
        initRecylerView();

        adapter = new AddressManageAdapter(mContext, mList);
        recyclerView.setAdapter(adapter);
    }
    private void initRecylerView() {

        //设置EmptyView
        View emptyView = View.inflate(mContext, R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        recyclerView.setEmptyView(emptyView);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        //设置是否开启上拉加载
        recyclerView.setLoadingMoreEnabled(true);
        //设置是否开启下拉刷新
        recyclerView.setPullRefreshEnabled(true);
        //设置是否显示上次刷新的时间
        recyclerView.displayLastRefreshTime(false);
//        recyclerView.setRefreshLimitHeight(DimenUtil.dip2px(mActivity,50));
    }
    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("选择地址");
    }

    @Override
    public void initListener() {
        //设置刷新回调
        recyclerView.setPullToRefreshListener(this);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(mContext,AddNewAddressActivity.class);
                startActivityForResult(intent,0);
            }
        });
        adapter.setOnItemClickListener(new AddressManageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AddressListResp.Address resp = mList.get(position);
                if(showDialog){
                    showConfirmDialog(resp);
                }
            }

            @Override
            public void onDelete(final int position) {

                DelAddressApi api=new DelAddressApi(mList.get(position).RECORD_ID,SpUtil.getString(SpUtil.MEMBER_MOBILE,""));
                //删除接口
                HttpManager.getInstance().dealHttp(AddressManageActivity.this, api, new OnNextListener<HttpResp>() {
                    @Override
                    public void onNext(HttpResp resp) {
                        if(resp.isOk()){
                            mList.remove(position);
                            adapter.notifyDataSetChanged();
                        }
                        else{
                            ToastUtil.showToast(mContext,resp.message);
                        }
                    }
                });

            }

            @Override
            public void onEdit(int position) {
                AddressListResp.Address resp=mList.get(position);
                Intent intent=new Intent(mContext,AddNewAddressActivity.class);
                intent.putExtra(AddNewAddressActivity.EXTRA_DATA,resp);
                startActivityForResult(intent,0);
            }
        });
    }

    @Override
    public void loadData() {
        getAddrList(1);
    }
    private void showConfirmDialog(final AddressListResp.Address addr) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_addr_select, null);
        TextView tvReceiver = (TextView) view.findViewById(R.id.tvReceiver);
        TextView tvReceiverPhone = (TextView) view.findViewById(R.id.tvReceiverPhone);
        TextView tvReceiverAddr1 = (TextView) view.findViewById(R.id.tvReceiverAddr1);
        TextView tvReceiverAddr2 = (TextView) view.findViewById(R.id.tvReceiverAddr2);

        TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
        tvReceiver.setText("收货人："+addr.SH_NAME);
        tvReceiverPhone.setText("手    机："+addr.SH_MOBILE);
        tvReceiverAddr1.setText(addr.PROVINCE_NAME+" "+addr.CITY_NAME+" "+addr.DISTRICT_NAME);
        tvReceiverAddr2.setText(addr.SH_ADDRESS);
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
                Intent intent=new Intent();
                intent.putExtra("data",addr);
                setResult(RESULT_OK,intent);
                finish();
            }
        });

        myDialog = new MyDialog(this, view, Gravity.CENTER);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0&&resultCode==RESULT_OK){
            loadData();
        }
    }

    private void getAddrList(final int page){
//        SpUtil.putString(SpUtil.MEMBER_ID,"152286");
//        SpUtil.putString(SpUtil.MEMBER_MOBILE,"18310106505");
        String mobile=SpUtil.getString(SpUtil.MEMBER_MOBILE,"");
        if(StringUtil.isEmpty(mobile)){
            return;
        }
        AddressListApi api=new AddressListApi(mobile,page);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<AddressListResp>>() {
            @Override
            public void onNext(HttpResp<AddressListResp> resp) {
                if (page == 1) {//下拉刷新操作
                    if (resp != null) {
                        recyclerView.setRefreshComplete();
                        if (resp.isOk()) {
                            mPage = 1;
                            mList.clear();
                            if (resp.data != null &&resp.data.ADDRESS_LIST!=null&& resp.data.ADDRESS_LIST.size() > 0) {
                                mList.addAll(resp.data.ADDRESS_LIST);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.showToast(mContext, resp.message);
                        }
                    } else {
                        recyclerView.setRefreshFail();
                    }
                } else {
                    if (resp != null) {
                        recyclerView.setLoadMoreComplete();
                        if (resp.isOk()) {
                            if (resp.data != null &&resp.data.ADDRESS_LIST!=null&& resp.data.ADDRESS_LIST.size() > 0){
                                mPage = page;
                                mList.addAll(resp.data.ADDRESS_LIST);
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUtil.showToast(mContext, getString(R.string.no_more_data));
                            }
                        } else {
                            ToastUtil.showToast(mContext, resp.message);
                        }
                    } else {
                        recyclerView.setLoadMoreFail();
                    }
                }
            }
            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page == 1) {
                    recyclerView.setRefreshFail();
                } else {
                    recyclerView.setLoadMoreFail();
                }
            }
        });
    }
    @Override
    public void onRefresh() {
        getAddrList(1);
    }

    @Override
    public void onLoadMore() {
        getAddrList(mPage+1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myDialog!=null&&myDialog.isShowing()){
            myDialog.dismiss();
        }
    }
}
